package com.tzy.note.base.thread.sync;

/**
 * 不安全的取钱
 * 两个人去银行取钱，帐户
 * 线程不安全的来源：就是每一个线程内存都是各自的
 */
public class UnsafeBank {
    public static void main(String[] args) {
        //两个人共同的帐户
        Account account = new Account(100,"结婚基金");

        Drawing you = new Drawing(account,50,"tzy");
        Drawing wife = new Drawing(account,100,"tln");

        you.start();
        wife.start();
    }
}

class Account{
    int money; //余额
    String name; //卡名
    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//银行：模拟取款
class Drawing extends Thread{
    Account account;
    //取了多少钱
    int drawingMoney;
    //现在还有多少钱
    int nowMoney;

    public Drawing(Account account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }
    //取钱，synchronized 默认锁的是this
    @Override
    public void run() { //如果在run方法加synchronized 锁的是this(这里也就是Drawing对象)，但是我们操作的增删改的对象是account
        //锁的对象就是变化的量,需要增鹏改的对象，这里变化的量的对象是account,所以只能在代码块中加synchronized，
        //如果synchronized加在方法上锁的是Drawing对象，synchronized默认锁的是this
        synchronized (account){
            //判断有没有钱
            if(account.money - drawingMoney < 0){
                System.out.println(Thread.currentThread().getName() + "钱不够，取不了");
                return;
            }
            try {
                //sleep：放大问题发现性
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡内余额=余额-要取的钱
            account.money = account.money-drawingMoney;
            //你手里的钱
            nowMoney = nowMoney + drawingMoney;
            System.out.println(account.name + "卡内余额为：" + account.money);
            //Thread.currentThread().getName() == this.getName()
            System.out.println(this.getName() + "手里的钱：" + nowMoney);
        }
    }
}